﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
//new
using HK;
using System.Runtime.InteropServices;
using System.IO;
using System.Drawing;

namespace JKZP
{
    public class HKJKCamera:JKCamera
    {
        public HKJKCamera()
        {
            m_Type = PP.JKCAMERATYPE.HAIKANG;
            m_Port = 8000;
            Init();
        }
        public override void Init() 
        {
            m_LoginID = -1;//海康-1代表失败
            m_Channel = 1;//通道从1开始
            m_PlayHandle = -1;//海康-1代表预览失败
            m_CamIsOpen = false;
            m_CDMC = "车道1";
            m_CDDM = "1";
            m_SnapCount = "3";
            m_TempPicName = "";
            m_FileName1 = "";
            m_FileName2 = "";
            m_FileName3 = "";
        }
        public override void Login() 
        {
            CHCNetSDK.NET_DVR_DEVICEINFO_V30 struDeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V30();
            m_LoginID = CHCNetSDK.NET_DVR_Login_V30(m_IP, m_Port, m_UserName, m_PassWord, ref struDeviceInfo);
        }
        public override void StartPreView(IntPtr handle) 
        {
            if ((m_LoginID >= 0) && (handle != IntPtr.Zero))
            {
                CHCNetSDK.NET_DVR_CLIENTINFO lpClientInfo = new CHCNetSDK.NET_DVR_CLIENTINFO();
                lpClientInfo.lChannel = m_Channel;
                lpClientInfo.lLinkMode = 0x0000;
                lpClientInfo.sMultiCastIP = "";
                lpClientInfo.hPlayWnd = handle;
                m_PlayHandle = CHCNetSDK.NET_DVR_RealPlay_V30(m_LoginID, ref lpClientInfo, null, IntPtr.Zero, 1);//1--请求码流过程是否阻塞
                if (m_PlayHandle > 0) m_CamIsOpen = true;
            }
        }
        public override bool CaptureOnePic(string group,string index, JKCamera m_CurrentCam) 
        { 
            if ((m_LoginID >= 0) && (m_PlayHandle >= 0))
            {
                m_TempPicName = PP.gTempFolder + group + "_" + index + "_" + m_CurrentCam.m_IP + ".jpg";
                CHCNetSDK.NET_DVR_JPEGPARA jpgparam = new CHCNetSDK.NET_DVR_JPEGPARA();
                jpgparam.wPicSize = 9;
                jpgparam.wPicQuality = 0;
                return CHCNetSDK.NET_DVR_CaptureJPEGPicture(m_LoginID, m_Channel, ref jpgparam, m_TempPicName);
                //return CHCNetSDK.NET_DVR_CapturePicture(m_PlayHandle, m_TempPicName);//bmp抓拍
            }
            return false;
        }

        public override bool SaveOneGroup(string group) 
        {
            if (PP.gJKRecordEnable == true)
            {
                return (SaveOnePic(group, "1") && SaveOnePic(group, "2") && SaveOnePic(group, "3") && SaveJKRecord());
            }
            else
            {
                return (SaveOnePic(group, "1") && SaveOnePic(group, "2") && SaveOnePic(group, "3"));
            }
        }


        private bool SaveOnePic(string group,string index)
        {
            bool ans = false;
            string splitor = "\\";
            try
            {
                //转换bmp为jpg
                string jpgfile = PP.gTempFolder + group + "_" + index + ".jpg";
                byte[] pic = null;
                byte[] picWithTail =null;
                if (File.Exists(jpgfile))
                {
                    pic = File.ReadAllBytes(jpgfile);
                }

                if (pic != null)
                {
                    //计算保存路径
                    string jkPicName = MakePicName(index,PP.gJKNameTypeList, PP.gJKNameTextList);
                    string jkSubPath = "";
                    if (PP.gJKSaveBySubFolder)
                    {
                        jkSubPath = MakeSubFolder(PP.gJKFolderTypeList);
                    }
                    string jkPath = PP.gJKSavePath + jkSubPath;
                    if (!Directory.Exists(jkPath)) Directory.CreateDirectory(jkPath);

                    //准备数据
                    if (PP.gJARITailEnable == true)
                    {
                        PP.structJariPicInfo info = new PP.structJariPicInfo();
                        info.m_Info1 = m_WFXWDM;
                        info.m_Info2 = index;
                        info.m_Info3 = "";
                        info.m_Info4 = m_HPHM;
                        info.m_Info5 = "0";
                        info.m_Info6 = "";
                        info.m_Info7 = "";
                        info.m_Info8 = "";
                        info.m_Info9 = "";
                        info.m_Info10 = "";
                        info.m_Info11 = "";
                        info.m_Info12 = m_CameraName;
                        info.m_Info13 = "";
                        info.m_Info14 = PP.gUser.username;
                        info.m_Info15 = "";
                        info.m_Info16 = "";
                        info.m_Info17 = m_RoadID;
                        info.m_Info18 = m_WFSJ.ToString("yyyy-MM-dd HH:mm:ss");
                        info.m_Info19 = "";
                        info.m_Info20 = "";
                        info.m_Info21 = "";
                        info.m_Info22 = "";
                        info.m_Info23 = "";
                        info.m_Info24 = "";
                        //叠加尾部信息
                        picWithTail = PP.AddTailToPic(info, pic);
                        //保存
                        File.WriteAllBytes(jkPath + splitor + jkPicName, picWithTail);
                    }
                    else
                    {
                        //保存
                        File.WriteAllBytes(jkPath + splitor + jkPicName, pic);
                    }

                    //生成3张图片名，辅助生成图片记录
                    if (index == "1")
                    {
                        m_FileName1 = jkPath + splitor + jkPicName;
                    }
                    else if (index == "2")
                    {
                        m_FileName2 = jkPath + splitor + jkPicName;
                    }
                    else if (index == "3")
                    {
                        m_FileName3 = jkPath + splitor + jkPicName;
                    }
                    else { }

                    if (File.Exists(jkPath + splitor + jkPicName))
                    {
                        File.Delete(jpgfile);
                        ans = true;
                    }
                }
            }
            catch(Exception er)
            {
                Console.WriteLine(er.Message);
            }
            return ans;
        }

        public override void StopPreView()
        {
            if (m_PlayHandle >= 0)
            {
                CHCNetSDK.NET_DVR_StopRealPlay(m_PlayHandle);
                m_PlayHandle = 0;
            }
        }
        public override void Logout() 
        {
            if (m_LoginID >= 0) CHCNetSDK.NET_DVR_Logout_V30(m_LoginID);
            m_LoginID = -1;
        }
        public override void Left(int speed, bool stop)
        {
            if ((m_LoginID >= 0) && (m_PlayHandle >= 0))
            {
                CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_PlayHandle, CHCNetSDK.PAN_LEFT, stop ? (uint)1 : (uint)0, (uint)speed);
            }
        }
        public override void Right(int speed, bool stop) 
        {
            if ((m_LoginID >= 0) && (m_PlayHandle >= 0))
            {
                CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_PlayHandle, CHCNetSDK.PAN_RIGHT, stop ? (uint)1 : (uint)0, (uint)speed);
            }
        }
        public override void Up(int speed, bool stop) 
        {
            if ((m_LoginID >= 0) && (m_PlayHandle >= 0))
            {
                CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_PlayHandle, CHCNetSDK.TILT_UP, stop ? (uint)1 : (uint)0, (uint)speed);
            }
        }
        public override void Down(int speed, bool stop)
        {
            if ((m_LoginID >= 0) && (m_PlayHandle >= 0))
            {
                CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_PlayHandle, CHCNetSDK.TILT_DOWN, stop ? (uint)1 : (uint)0, (uint)speed);
            }
        }
        public override void ZoomIn(int speed, bool stop) 
        {
            if ((m_LoginID >= 0) && (m_PlayHandle >= 0))
            {
                CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_PlayHandle, CHCNetSDK.ZOOM_IN, stop ? (uint)1 : (uint)0, (uint)speed);
            }
        }
        public override void ZoomOut(int speed, bool stop) 
        {
            if ((m_LoginID >= 0) && (m_PlayHandle >= 0))
            {
                CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_PlayHandle, CHCNetSDK.ZOOM_OUT, stop ? (uint)1 : (uint)0, (uint)speed);
            }
        }
        public override void PTZ3D(Rectangle WinRect, Point pointStart, Point pointEnd)
        {
            if ((m_LoginID >= 0) && (m_PlayHandle >= 0))
            {
                try
                {
                    //该结构体中的坐标值与当前预览显示框的大小有关，
                    //现假设预览显示框为352*288，我们规定原点为预览显示框左上角的顶点，前四个参数计算方法如下：
                    //xTop = 鼠标当前所选区域的左上角坐标的值*255/352；
                    //xBottom = 鼠标当前所选区域的右下角坐标的值*255/352；
                    //yTop = 鼠标当前所选区域的左下角坐标的值*255/288；
                    //yBottom = 鼠标当前所选区域的右下角坐标的值*255/288；
                    //缩小条件：xBottom减去xTop的值大于2。
                    //放大条件：xBottom减去xTop的值大于0，且yBottom减去yTop的值大于0。
                    //bCounter画框方向：1- 左上，2- 右上，3- 左下，4- 右下
                    CHCNetSDK.NET_DVR_POINT_FRAME frame = new CHCNetSDK.NET_DVR_POINT_FRAME();
                    frame.xTop = pointStart.X * 255 / WinRect.Width;
                    frame.yTop = pointStart.Y * 255 / WinRect.Height;
                    frame.xBottom = pointEnd.X * 255 / WinRect.Width;
                    frame.yBottom = pointEnd.Y * 255 / WinRect.Height;
                    frame.bCounter = 0;
                    if (frame.xTop < frame.xBottom)
                    {
                        if (frame.yTop < frame.yBottom)
                        {
                            frame.bCounter = 1;
                        }
                        else
                        {
                            frame.bCounter = 3;
                        }
                    }
                    else
                    {
                        if (frame.yTop < frame.yBottom)
                        {
                            frame.bCounter = 2;
                        }
                        else
                        {
                            frame.bCounter = 4;
                        }
                    }
                    CHCNetSDK.NET_DVR_PTZSelZoomIn(m_PlayHandle, ref frame);
                }
                catch { }
            }
        }
        public override void CallPreSetPoint(int index)
        {
            if ((m_LoginID >= 0) && (m_PlayHandle >= 0))
            {
                CHCNetSDK.NET_DVR_PTZPreset(m_PlayHandle, CHCNetSDK.GOTO_PRESET, (uint)index);
            }
        }
        public override bool SavePreSetPoint(int index)
        {
            if ((m_LoginID >= 0) && (m_PlayHandle >= 0))
            {
                return CHCNetSDK.NET_DVR_PTZPreset(m_PlayHandle, CHCNetSDK.SET_PRESET, (uint)index);
            }
            return false;
        }
        public override void ShutDown() 
        {
            StopPreView();
            Logout();
            Init();
        }

        public override DateTime GetDeviceTime()
        {
            //校时
            DateTime now = DateTime.Now;
            CHCNetSDK.NET_DVR_TIME CurTime = new CHCNetSDK.NET_DVR_TIME();
            IntPtr ptime = Marshal.AllocHGlobal(Marshal.SizeOf(CurTime));

            uint lpBytesReturned=0;
            try
            {
                Marshal.StructureToPtr(CurTime, ptime, true);
                CHCNetSDK.NET_DVR_GetDVRConfig(m_LoginID, CHCNetSDK.NET_DVR_GET_TIMECFG, 0, ptime, (uint)Marshal.SizeOf(CurTime), ref lpBytesReturned);
                object obj = Marshal.PtrToStructure(ptime, typeof(CHCNetSDK.NET_DVR_TIME));
                if (obj != null)
                {
                    CurTime = (CHCNetSDK.NET_DVR_TIME)obj;
                    now = new DateTime((int)CurTime.dwYear, (int)CurTime.dwMonth, (int)CurTime.dwDay, (int)CurTime.dwHour, (int)CurTime.dwMinute, (int)CurTime.dwSecond);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(ptime);
            }
            return now;
        }

        public override void CheckTime()
        {
            //校时
            DateTime now = DateTime.Now;
            CHCNetSDK.NET_DVR_TIME CurTime = new CHCNetSDK.NET_DVR_TIME();
            CurTime.dwYear = (uint)now.Year;
            CurTime.dwMonth = (uint)now.Month;
            CurTime.dwDay = (uint)now.Day;
            CurTime.dwHour = (uint)now.Hour;
            CurTime.dwMinute = (uint)now.Minute;
            CurTime.dwSecond = (uint)now.Second;


            IntPtr ptime = Marshal.AllocHGlobal(Marshal.SizeOf(CurTime));
            try
            {
                Marshal.StructureToPtr(CurTime, ptime, true);
                CHCNetSDK.NET_DVR_SetDVRConfig(m_LoginID, CHCNetSDK.NET_DVR_SET_TIMECFG, 0, ptime, (uint)Marshal.SizeOf(CurTime));
            }
            finally
            {
                Marshal.FreeHGlobal(ptime);
            }
        }
        public override void Play(IntPtr handle)
        {
            Init();
            Login();
            StartPreView(handle);
        }
        public override void FindFile(DateTime from, DateTime to)
        {
            return;
        }
        public override void StartPlayVideo(int index)
        {
            return;
        }
        public override void StopPlayVideo(int index)
        {
            return;
        }
        public override void PausePlayVideo(int index)
        {
            return;
        }
        public override void FowardPlayVideo(int index)
        {
            return;
        }
        public override void BackPlayVideo(int index)
        {
            return;
        }
    }
}
